package google.architecture.coremodel.datamodel.http.repository;

import android.arch.persistence.room.Room;
import android.content.Context;

import java.util.List;

import google.architecture.coremodel.datamodel.http.ApiClient;
import google.architecture.coremodel.datamodel.http.db.ShoppingCarItemDatabase;
import google.architecture.coremodel.datamodel.http.entities.BaseData;
import google.architecture.coremodel.datamodel.http.entities.ClassifyData;
import google.architecture.coremodel.datamodel.http.entities.LoginData;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.entities.OrderData;
import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.datamodel.http.entities.TerInfoData;
import google.architecture.coremodel.exception.LackOfStockException;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

/**
 * Created by ghcui on 20178/06/03
 * 自动售药机接口
 */

public class AutoVenderDataRepository {
    private ShoppingCarItemDatabase mDatabase;

    public AutoVenderDataRepository(Context context) {
        mDatabase = Room.databaseBuilder(context, ShoppingCarItemDatabase.class, "autovender.db").build();
    }

    public Observable<TerInfoData> getTerInfo(String deviceId) {
        Observable<TerInfoData> observableForProductList = ApiClient.getAutoVenderDataService().getTerInfo(deviceId);
        return observableForProductList;
    }

    public Observable<ProductData> getProductListRepository(Integer typeId, String terNo, int page, int size) {
        Observable<ProductData> observableForProductList = null;
        if (typeId == null) {
            observableForProductList = ApiClient.getAutoVenderDataService().getProductList(terNo, page, size);
        } else {
            observableForProductList = ApiClient.getAutoVenderDataService().getProductList(typeId, terNo, page, size);
        }
        return observableForProductList;
    }

    public Observable<ProductData> searchDrug(String words, String terNo, int page, int size) {
        Observable<ProductData> observableForProductList = ApiClient.getAutoVenderDataService().searchDrug(words, terNo, page, size);
        return observableForProductList;
    }

    public Observable<ClassifyData> getClassify(String terNo) {
        Observable<ClassifyData> observableForGetClassify = ApiClient.getAutoVenderDataService().getClassify(terNo);
        return observableForGetClassify;
    }

    public Observable<ProductData> searchDrugByColumn(String terNo,int unit,int row,int column ,int page, int size) {
        Observable<ProductData> observableForProductList = ApiClient.getAutoVenderDataService().searchDrugByColumn(terNo, unit,row,column, page, size);
        return observableForProductList;
    }

    public Observable<List<ShoppingCarItem>> getShoppingCarListRepository() {
        Observable<List<ShoppingCarItem>> observableForShoppingCarList = Observable.create(new ObservableOnSubscribe<List<ShoppingCarItem>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ShoppingCarItem>> emitter) throws Exception {
                List<ShoppingCarItem> items = mDatabase.getShoppingCarItemDao().getItems();
                emitter.onNext(items);
                emitter.onComplete();
            }
        });
        return observableForShoppingCarList;
    }

    public Observable<OrderData> creatTrade(String terNo, int paymentType, String drugInfos) {
        return ApiClient.getAutoVenderDataService().creatTrade(terNo, paymentType, drugInfos);
    }

    public Observable<ShoppingCarItem> add2ShoppingCar(ProductData.Product product, int count) {
        Observable<ShoppingCarItem> observableForShoppingCarList = Observable.create(new ObservableOnSubscribe<ShoppingCarItem>() {
            @Override
            public void subscribe(ObservableEmitter<ShoppingCarItem> emitter) {
                int stock=product.getDrugQuantity();
                //原先已经加入购物车的数量
                int oldCount = getItemCountById(product.getPlanId());
                int newCount = count + oldCount;
                if (newCount > stock) {
                    emitter.onError(new LackOfStockException("库存不足"));
                    return;
                }
                long time=System.currentTimeMillis();
                ShoppingCarItem shoppingCarItem=new ShoppingCarItem();
                shoppingCarItem.setStackCount(product.getDrugQuantity());
                shoppingCarItem.setId(product.getPlanId());
                shoppingCarItem.setColumnNo(product.getColumnNo());
                shoppingCarItem.setUnitNo(product.getUnitNo());
                shoppingCarItem.setLineNo(product.getLineNo());
                shoppingCarItem.setPrice(product.getPrice());
                shoppingCarItem.setTitle(product.getTitle());
                shoppingCarItem.setThumb(product.getThumb());
                shoppingCarItem.setCount(count);
                shoppingCarItem.setCommand(product.getCommand());
                shoppingCarItem.setCreattime(time);
                shoppingCarItem.setLastModified(time);
                //表示之前已经加入过购物车，现在只需要更新即可
                shoppingCarItem.setCount(newCount);
                if (oldCount > 0) {
                    mDatabase.getShoppingCarItemDao().updateItem(shoppingCarItem);
                } else {
                    mDatabase.getShoppingCarItemDao().insertItem(shoppingCarItem);
                }
                emitter.onNext(shoppingCarItem);
                emitter.onComplete();
            }
        });
        return observableForShoppingCarList;
    }

    public Observable<Boolean> deleteShoppingCar(final ShoppingCarItem... items) {
        Observable<Boolean> observableForClearShoppingCar = Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) {
                mDatabase.getShoppingCarItemDao().deleteItem(items);
                emitter.onNext(true);
                emitter.onComplete();
            }
        });
        return observableForClearShoppingCar;
    }

    public Observable<Boolean> clearShoppingCart() {
        Observable<Boolean> observableForClearShoppingCar = Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) {
                mDatabase.getShoppingCarItemDao().deleteAll();
                emitter.onNext(true);
                emitter.onComplete();
            }
        });
        return observableForClearShoppingCar;
    }

    public Integer getItemCountById(final String id) {
        int count = 0;
        List<ShoppingCarItem> items = mDatabase.getShoppingCarItemDao().getItemById(id);
        if (items != null && !items.isEmpty()) {
            count = items.get(0).getCount();
        }
        return count;
    }


    public Observable<Integer> getItemCount(final String id) {
        Observable<Integer> observableForeGetItemCountById = Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) {
                int count = 0;
                List<ShoppingCarItem> items = mDatabase.getShoppingCarItemDao().getItemById(id);
                if (items != null && !items.isEmpty()) {
                    count = items.get(0).getCount();
                }
                emitter.onNext(count);
                emitter.onComplete();
            }
        });
        return observableForeGetItemCountById;
    }

    public Observable<Boolean> updateShoppingCar(final ShoppingCarItem... items) {
        Observable<Boolean> observableForClearShoppingCar = Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) {
                mDatabase.getShoppingCarItemDao().updateItem(items);
                emitter.onNext(true);
                emitter.onComplete();
            }
        });
        return observableForClearShoppingCar;
    }

    public Observable<BaseData> addDrug(String planId,int drugQuantity,int operNum ) {
        Observable<BaseData> observableForAddDrug = ApiClient.getAutoVenderDataService().addDrug(planId,drugQuantity,operNum);
        return observableForAddDrug;
    }

    public Observable<BaseData> delDrug(String terNo,String planId) {
        Observable<BaseData> observableForDelDrug = ApiClient.getAutoVenderDataService().delDrug(terNo,planId);
        return observableForDelDrug;
    }

    public Observable<LoginData> login(String terNo,String password) {
        Observable<LoginData> observableForLogin = ApiClient.getAutoVenderDataService().login(terNo,password);
        return observableForLogin;
    }

    public Observable<BaseData> putTerEnv(String terNo, int temp,int hum) {
        Observable<BaseData> observableForAddDrug = ApiClient.getAutoVenderDataService().putTerEnv(terNo,temp,hum);
        return observableForAddDrug;
    }

    public Observable<BaseData> tradeRefund(String tradeNo) {
        Observable<BaseData> observableForAddDrug = ApiClient.getAutoVenderDataService().tradeRefund(tradeNo);
        return observableForAddDrug;
    }
    public Observable<BaseData> saveMistake(String terNo, String errorCode) {
        Observable<BaseData> observableForAddDrug = ApiClient.getAutoVenderDataService().saveMistake(terNo,errorCode);
        return observableForAddDrug;
    }


}